package com.base.leetcode;

import com.base.dataStructure.Tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: hdhao
 * @Create: 2023/4/5 - 19:04
 * @Version: v1.0
 */
//二叉树的最大深度-使用后序遍历求解
public class Leetcode104 {
    /*
        思路：
            1、得到左子树深度,得到右子树深度,二者最大者加一,就是本节点深度
            2、因为需要先得到左右子树深度,很显然是后续遍历的典型应用
            3、关于深度的定义:从根出发,离根最远的节点总边数,
                注意:leetcode中的深度定义要多加一
     */
    //递归方法求解
    public int maxDepth(TreeNode node) {
        if (node == null) {
            return 0;
        }
        if (node.left == null && node.right == null) {
            return 1;
        }
        int left = maxDepth(node.left);
        int right = maxDepth(node.right);
        return Integer.max(left, right) + 1;
    }
    //非递归方式,使用后序遍历的方式
    public int maxDepth1(TreeNode root) {
        TreeNode curr = root;
        TreeNode pop = null;
        LinkedList<TreeNode> stack = new LinkedList<>();
        //栈的最大高度
        int max = 0;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                int size = stack.size();
                if (size > max) {
                    max = size;
                }
                curr = curr.left;
            } else {
                TreeNode peek = stack.peek();
                if (peek.right == null || peek.right == pop) {
                    pop = stack.pop();
                } else {
                    curr = peek.right;
                }
            }
        }
        return max;
    }

    //使用层序遍历的方式
    public int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        //记录每层有几个元素
//        int c1 = 1;
        int depth = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
//            int c2 = 0;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) {
                    queue.offer(poll.left);
//                    c2++;
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
//                    c2++;
                }
            }
            depth++;
//            c1 = c2;
        }
        return depth;
    }
}
